package com.frank.libandroid.util;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

public class Bus {
    public interface Receiver {
        void onMessage(Object... value);
    }

    private static Map<String, List<WeakReference<Receiver>>> mObserverMap = new HashMap<>();

    public static void emit(String key, Object... value) {
        List<WeakReference<Receiver>> weakReferences = mObserverMap.get(key);
        if (weakReferences != null) {
            Iterator<WeakReference<Receiver>> iterator = weakReferences.iterator();
            while (iterator.hasNext()) {
                Receiver observer = iterator.next().get();
                if (observer == null) {
                    iterator.remove();
                }
                observer.onMessage(value);
            }
        }
    }

    public static void register(Receiver observer) {
        mObserverMap.computeIfAbsent(observer.getClass().getName(), new Function<String, List<WeakReference<Receiver>>>() {
            @Override
            public List<WeakReference<Receiver>> apply(String s) {
                return new ArrayList<>();
            }
        }).add(new WeakReference<>(observer));
    }
}
